package com.suredy.app.project.ctrl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.app.project.constants.DicKey;
import com.suredy.app.project.model.ProjectCost;
import com.suredy.app.project.service.ProjectCostSrv;
import com.suredy.core.service.DictionarySrv;

/**
 * 费用支出表单控制器
 * 
 * @author VIVID.G
 * @since 2015-7-30
 * @version v0.1
 */
@Controller
@RequestMapping("/cost/form")
public class CostFormCtrl {

	@Autowired
	private ProjectCostSrv costSrv;

	@Autowired
	private DictionarySrv dictionarySrv;

	@RequestMapping(method = RequestMethod.GET)
	public String costForm(String id, String projId, Model model) {
		String view = "app/project/cost-form";

		if (StringUtils.isBlank(projId)) {
			model.addAttribute("noProjectId", true);
			return view;
		}

		ProjectCost cost = null;

		if (StringUtils.isBlank(id)) {
			// 新建
			cost = new ProjectCost();
		} else {
			// 修改
			cost = this.costSrv.get(id);

			if (cost == null || StringUtils.isBlank(cost.getId())) {
				model.addAttribute("notFound", true);
				return view;
			}
		}

		model.addAttribute("projId", projId);
		model.addAttribute("costName", this.costName());
		model.addAttribute("data", cost);

		return view;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public boolean saveCostForm(ProjectCost cost) {
		if (cost.getProject() == null)
			return false;

		if (StringUtils.isBlank(cost.getId()))
			cost.setId(null);

		cost = this.costSrv.saveOrUpdate(cost);

		return cost != null && !StringUtils.isBlank(cost.getId());
	}

	@RequestMapping(value = "/update-status", method = RequestMethod.POST)
	@ResponseBody
	public boolean updateStatus(String id, boolean status) {
		if (StringUtils.isBlank(id))
			return false;

		int count = this.costSrv.updateStatus(id, status);

		return count == 1;
	}

	private List<String> costName() {
		return this.dictionarySrv.getVals(DicKey.COST_NAME);
	}

}
